/**
 * 
 */
package com.fang.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import com.fang.browser.support.SocialUserInfo;
import com.fang.dto.User;
import com.fang.dto.UserQueryCondition;
import com.fang.exception.UserNotExistException;
import com.fasterxml.jackson.annotation.JsonView;

@RestController
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private ProviderSignInUtils providerSignInUtils;
	
	/**
	 * 用户必须存在UserConnection表用于存在用户在QQ上获取的基本信息
	 */
	@PostMapping("/regist")
	public void regist(User user, HttpServletRequest request) {
		
		//不管是注册用户还是绑定用户，都会拿到一个用户唯一标识。
		String userId = user.getUsername();
		providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));
//		appSingUpUtils.doPostSignUp(new ServletWebRequest(request), userId);
	}
	
	@GetMapping("/me")
	public Object getCurrentUser(Authentication user, HttpServletRequest request) throws Exception {
		
//		String token = StringUtils.substringAfter(request.getHeader("Authorization"), "bearer ");
//		
//		Claims claims = Jwts.parser().setSigningKey(securityProperties.getOauth2().getJwtSigningKey().getBytes("UTF-8"))
//					.parseClaimsJws(token).getBody();
//		
//		String company = (String) claims.get("company");
//		
//		System.out.println(company);
		
		return user;
	}
	
	/**
	 * 请求经过socialAuthencationProvider中之后，
	 * @param request
	 * @return
	 */
	@GetMapping("/social/user")
	public SocialUserInfo getSocialUserInfo(HttpServletRequest request){
		SocialUserInfo socialUserInfo = new SocialUserInfo();
		Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
		socialUserInfo.setProviderId(connection.getKey().getProviderId());
		socialUserInfo.setProviderUserId(connection.getKey().getProviderUserId());
		socialUserInfo.setNickName(connection.getDisplayName());
		socialUserInfo.setHeading(connection.getImageUrl());
		return socialUserInfo;
		
	}

	/**
	 * @JsonView 显示那些字段
	 * @requestParam 默认要求是必填的
	 * @param username
	 * @return
	 */
	@GetMapping(value = "/user")
	@JsonView(User.UserSimpleView.class)
	public List<User> query(UserQueryCondition condition) {

		System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE));

		List<User> users = new ArrayList<>();
		users.add(new User());
		users.add(new User());
		users.add(new User());
		return users;
	}

	/**
	 * @PathVariable 把id作为值传入到java方法里面
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	public User getInfo(@PathVariable String id) {
		
		throw new UserNotExistException(id);
	}

	/**
	 * 通过时间戳来前后端的传递 BindingResult
	 * @RequestBosy 读取Request请求上的body数据，使用系统默认的HttpMessageConverter进行解析然后把数据绑定到相应的对象上
	 * @param user
	 * @return
	 */
	@GetMapping(value = "/create")
	public User create(@Valid User user, BindingResult errors) {
		/**
		 * hibernate-valid
		 */
		if (errors.hasErrors()) {
			errors.getAllErrors().stream().forEach(error -> {
				FieldError fieldError = (FieldError) error;
				String message = fieldError.getField() + error.getDefaultMessage();
				System.out.println(error.getDefaultMessage());
			});
		}
		;
		System.out.println(user.getId());
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
		System.out.println(user.getBirthday());
		user.setId("1");
		return user;
	}

	@PutMapping("")
	public User update(@Valid @RequestBody User user, BindingResult errors) {
		System.out.println(user.getId());
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
		System.out.println(user.getBirthday());
		user.setId("1");
		return user;
	}

	@DeleteMapping("/{id:\\d+}")
	public void delete(@PathVariable String id) {
		System.out.println(id);
	}

}
